from flask import Blueprint, request, jsonify, current_app, g
from werkzeug.utils import secure_filename
import os


from app.utils.file_upload import save_file
from app.utils.response import success, error

base_bp = Blueprint('base', __name__)

@base_bp.route('/upload', methods=['POST'])
def upload_file():
    try:
        # 检查是否有文件
        if 'file' not in request.files:
            return error(message='未上传文件', code=400)
            
        file = request.files['file']
        if file.filename == '':
            return error(message='未选择文件', code=400)
            
        # 获取上传目录参数，默认为 common
        folder = request.form.get('folder', 'common')
        
        # 检查文件类型
        allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx'}
        if not ('.' in file.filename and file.filename.rsplit('.', 1)[1].lower() in allowed_extensions):
            return error(message='不支持的文件类型', code=400)
            
        # 保存文件
       
        file_path = save_file(file, folder)
        current_app.logger.info(f"文件上传成功: {file_path}")
        
        return success(
            data={
                'path': file_path,
                'filename': file.filename
            },
            message='文件上传成功'
        )
        
    except Exception as e:
        current_app.logger.error(f"文件上传失败: {str(e)}")
        return error(message=f'文件上传失败: {str(e)}', code=500)



